var config = require('../config/config.js')();
var _urlAccessToken = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CorpID&corpsecret=$Secret';
var _urlUserInfo = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$ACCESS_TOKEN&userid=$userid';
var _urlAllUser = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=$ACCESS_TOKEN&department_id=1&fetch_child=1&status=0';
var _urlUseridByCode = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$ACCESS_TOKEN&code=$code&agentid=$agentid';
var _urlCode = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=$CorpID&redirect_uri=$REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
var _urlSendMsg = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$ACCESS_TOKEN';


var _CorpID = config.weixin.CorpID,
	_Secret = config.weixin.Secret;

function UrlUtils() {}
module.exports = exports = UrlUtils;

var wp = UrlUtils.prototype;

var urlAccessToken = null;
wp.getUrlAccessToken = function() {
	if (!urlAccessToken) {
		urlAccessToken = _urlAccessToken.replace(/\$CorpID/g, _CorpID).replace(/\$Secret/g, _Secret);
	}
	return urlAccessToken;
}



var urlUserInfo = null;
wp.getUrlUserInfo = function(userid, accessToken) {
	if (!urlUserInfo) {
		urlUserInfo = _urlUserInfo.replace(/\$userid/g, userid).replace(/\$ACCESS_TOKEN/g, accessToken);
	}
	return urlUserInfo;
}

var urlAllUser = null;
wp.getUrlAllUser = function(accessToken) {
	if (!urlAllUser) {
		urlAllUser = _urlAllUser.replace(/\$ACCESS_TOKEN/g, accessToken);
	}
	return urlAllUser;
}


var urlUseridByCode = null;
wp.getUrlUserIdByCode = function(accessToken, code) {
	if (!urlUseridByCode) {
		urlUseridByCode = _urlUseridByCode.replace(/\$ACCESS_TOKEN/g, accessToken);
		urlUseridByCode = urlUseridByCode.replace(/\$agentid/g, config.weixin.agentId);
	}
	var url = urlUseridByCode.replace(/\$code/g, code);
	return url;
}

var urlCode = null;
wp.getUrlCode = function() {
	if (!urlCode) {
		redirectUri = config.weixin.redirectUri;
		redirectUri = encodeURI(redirectUri);
		urlCode = _urlCode.replace(/\$CorpID/g, _CorpID);
		urlCode = urlCode.replace(/\$REDIRECT_URI/g, redirectUri);
	}
	return urlCode;
}

var urlSendMsg = null;
wp.getUrlSendMsg = function(accessToken) {
	if (!urlSendMsg) {
		urlSendMsg = _urlSendMsg.replace(/\$ACCESS_TOKEN/g, accessToken);
	}
	return urlSendMsg;
}